<!-- 平台匹配组件 （租房） -->
<template>
  <div class="d-flex">
    <div class="flex-1 cell">{{ title }}</div>
    <!-- 匹配小区 -->
    <div class="flex-1 cell" v-loading="portVO.loading">
      <div v-show="!portVO.portResblockName && !portVO.loading" class="text-red">
        未匹配
      </div>
      <div v-show="portVO.portResblockName && !portVO.loading">
        {{ portVO.portResblockName }}
      </div>
    </div>

    <!-- 匹配 户室号 -->
    <div class="flex-3 cell" v-loading="portVO.hallRoomLoading">
      <div
        v-show="!portVO.hallRoomLoading && portVO.hallRoomNumber.length == 0 && portVO.portResblockName"
        style="margin: auto"
        class="fs-sm text-center"
      >
        加载失败,
        <el-button type="text" @click="handleRetryColumn">点击重试</el-button>
      </div>
      <div class="d-flex">
        <template v-for="item in portVO.hallRoomNumber">
          <el-input 
            v-model="portVO[item.key]" 
            :key="item.key" 
            style="margin: 0 5px" 
            :placeholder="item.title"
          ></el-input>
        </template>
      </div>
    </div>

    <!-- 总价 -->
    <div class="flex-1 cell">
      <el-input v-model="myTotalPrices">
        <i slot="suffix" style="font-style: normal">元/月</i>
      </el-input>
    </div>
    <!-- 面积 -->
    <div class="flex-1 cell">
      <el-input v-model="myBuildSize">
        <i slot="suffix" style="font-style: normal">平方米</i>
      </el-input>
    </div>
    <!-- 操作 -->
    <div class="flex-1 cell">
      <el-button size="mini" type="text" @click="handlePopShow">{{
        portVO.portResblockName ? "重新匹配小区" : "手工匹配小区"
      }}</el-button>
    </div>

    <!-- 手动匹配弹层 -->
    <el-dialog :visible.sync="popVisible" top="30vh" :close-on-click-modal="false" :show-close="true" width="600px">
      <span slot="title" class="d-flex ai-baseline">
        <span class="fs-xl" style="margin-left: 8px">手工匹配</span>
        <span>（注：输入小区或关键字后，需点击“搜索”按钮）</span>
      </span>
      <comManualMatch :popModel="popModel" :delId="delId"></comManualMatch>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="popVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePopConfirm">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import comTitleItem from "./com-title-item";
import comManualMatch from "./com-manual-match";
import { hallRoomNumber } from "@/config/house/houseDetailConfig";
import platform from "@/config/house/platform";
import {
  matchingResblock,
  matchingBuild,
} from "@/api/user";

export default {
  name: "ComRentMatchItem",
  components: {
    comTitleItem,
    comManualMatch,
  },
  props: {
    model: {
      type: Object,
      default() {
        return {};
      }
    },
    resblockName: {
      type: String,
      default: "",
    },
    noPortAccount: {
      type: Number,
      default: 0,
    },
    delId: String
  },
  data() {
    return {
      myTotalPrices: "",
      myBuildSize: "",
      handlePriceInputBlurTimer: null,
      handleTimer: null,
      intervalTime: 2000,
      totalTimes: 0,
      tryTimes: 0,
      popVisible: false,
      popResblockVisible: false, //选择小区的小弹层
      title: "",

      // 暂且只用了匹配小区相关数据
      popModel: {
        portResblockName: "", //端口小区名称
        portResblockId: "",

        platformResblockId: "", //平台小区id
        platformBuildId: "", //平台楼栋id
        platformUnitId: "", //平台单元ID
        platformDoorNumId: "", //平台门牌号ID

        portType: "", // 平台类型
        loading: false, //匹配小区加载
        searchKey: "", //搜索关键词

        housingEstateOptions: [], //匹配小区选项
      },
      // 端口信息
      portVO: {
        portResblockName: "", //端口小区名称
        portResblockId: "",

        portBuild: "", //栋/幢
        portBuildId: "",
        portUnit: "", //单元/号
        portUnitId: "",
        portDoorNum: "", //门牌
        portDoorNumId: "",

        platformResblockId: "", //平台小区id   (platform 代表安居客等平台)
        platformBuildId: "", //平台楼栋id
        platformUnitId: "", //平台单元ID
        platformDoorNumId: "", //平台门牌号ID

        portType: "", // 平台类型
        loading: false, //匹配小区加载。。。
        hallRoomLoading: false, //户室号加载。。。
        singleLoading: false, //单个户室号加载。。。
        isCheckingPrice: false, //校验价格中。。。
        isMatchingBuild: false, //匹配面积中。。。
        searchKey: "", //搜索关键词
        portTags: [], //平台标签
        hallRoomNumber,

        housingEstateOptions: [], //匹配小区选项
        buildUnitDoorOptions: [], //户室号的选项
        huShiHao: false, //是否支持手动输入
        totalPricesPassed: false, //是否总价通过校验
        totalPricesTimeout: false, //是否总价超时
        totalPricesIgnore: false, //是否总价忽略校验

        totalPrice: "",
        buildingSize: "",
      },
    };
  },

  created() {},

  mounted() {
    // console.log('mouted this.model=== ', this.model);
    this.myTotalPrices = this.model.totalPrice;
    this.myBuildSize = this.model.buildingSize;

    this.renderPort(this.model, this.resblockName);
    this.title = platform[this.portVO.portType];

    this.popModel.portType = this.portVO.portType;
  },

  computed: {
  },

  watch: {
    portVO: {
      handler(newVal, oldVal) {
        this.$emit("updateportvo", newVal);
      },
      deep: true,
    },

    myBuildSize(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.buildingSize = newValue;
    },

    myTotalPrices(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.totalPrice = newValue;
    },
  },

  beforeDestroy() {
    if (this.handleTimer) {
      clearTimeout(this.handleTimer);
      this.handleTimer = null;
    }
  },

  methods: {
    renderPort(data, resblockName) {
      Object.assign(this.portVO, data);

      // console.log('this.portVO== ', this.portVO)

      if (this.portVO.totalPricesPassed) {
        this.$emit("ontotalpricespassed", true);
      }
      if (this.portVO.totalPricesIgnore) {
        this.$emit("ontotalpricesignore", true);
      }

      // 可推表示填写完整了 (此处跟二手不一样 可推但是并没有户室号)
      let hallList = hallRoomNumber.filter((v) => !!data[v.key]);
      if (hallList.length >= 2) {
        this.portVO.hallRoomNumber = hallList
        
      } else {
        this.resetHuShiHao("portVO");

        // 已匹配过小区
        if (data.portResblockName) {
          this.getHshColumn("portVO", data);

          // 自动帮他匹配小区
        } else {
          if (this.noPortAccount==1) {
            this.portVO.hallRoomNumber = [];
            this.autoMatchingResblock("portVO", resblockName);
          }
        }
      }
    },

    // 自动匹配小区
    autoMatchingResblock(way, name) {
      this[way].loading = true;
      matchingResblock({
        delId: this.delId,
        portResblockName: (name || '').trim(),
        portType: this[way].portType,
        actionType: way == "portVO" ? 0 : 1,
        type: 1,
      }).then((content) => {
        this.tryTimes = 0;
        this[way].loading = false;

        if (content.length) {
          this[way].housingEstateOptions = content;
          if (way == "portVO") {
            this.handleChangePortResblockName(way, content[0].portResblockName);
          }

          if (way == "popModel") {
            // 搜索到小区
          }
        }
      }).catch(() => {
        let setSuccess = this.setTimer(() => {
          this.autoMatchingResblock(way, name);
          console.log("重新匹配。。。");
        });
        if (!setSuccess) {
          this[way].loading = false;
        }
      });
    },

    setTimer(fn) {
      if (this.tryTimes >= this.totalTimes) {
        this.tryTimes = 0;
        return false;
      }
      this.tryTimes = this.tryTimes + 1;
      if (this.handleTimer) {
        clearTimeout(this.handleTimer);
        this.handleTimer = null;
      }
      this.handleTimer = setTimeout(fn, this.intervalTime);
      return true;
    },

    // 匹配到小区
    handleChangePortResblockName(way, value) {
      const item = this[way].housingEstateOptions.find((v) => v.portResblockName == value);
      Object.assign(this[way], item);

      if (way == "portVO") {
        this.getHshColumn(way, item);
      }
    },

    // 获取某小区的户室号栏目数
    getHshColumn(way, info) {
      this[way].huShiHao = true;
      this[way].buildUnitDoorOptions = [];

      this[way].hallRoomLoading = true;
      this.resetHuShiHao(way);

      if (this[way].hallRoomNumber.length) {
        this[way].hallRoomNumber = [];
      }

      return matchingBuild({
        delId: this.delId,
        portResblockId: info.portResblockId,
        portType: this[way].portType,
        type: 1,
        platformResblockId: info.platformResblockId,
      }).then((content) => {
        this.tryTimes = 0;

        this[way].hallRoomLoading = false;
        if (content == "{}") {
          return;
        }
        let data = JSON.parse(content);

        const keys = ["isShowBuilding", "isShowUnit", "isShowHouse"];
        const arr = hallRoomNumber.filter((item, i) => data[keys[i]] == 1);
        this[way].hallRoomNumber = arr;

        // 恒定为手动输入
        this[way].huShiHao = true;
        
      }).catch(() => {
        let setSuccess = this.setTimer(() => {
          this.getHshColumn(way, info);
          // console.log("重新匹配几栏。。。");
        });
        if (!setSuccess) {
          this[way].hallRoomLoading = false;
        }
      });
    },

    // 重试户室号栏目
    handleRetryColumn() {
      this.getHshColumn("portVO", this.portVO);
    },

    resetHuShiHao(way) {
      this[way].portBuild = "";
      this[way].portBuildId = "";
      this[way].portUnit = "";
      this[way].portUnitId = "";
      this[way].portDoorNum = "";
      this[way].portDoorNumId = "";

      this[way].platformBuildId = "";
      this[way].platformUnitId = "";
      this[way].platformDoorNumId = "";

      this[way].huShiHao = false;
    },

    handlePopShow() {
      this.popVisible = true;

      this.popModel.searchKey = "";
      this.popModel.portResblockName = "";
      this.popModel.platformResblockId = "";
      this.popModel.housingEstateOptions = [];
    },

    handlePopConfirm() {
      if (this.popModel.platformResblockId) {
        this.portVO.portResblockName = this.popModel.portResblockName;
        this.portVO.portResblockId = this.popModel.portResblockId;
        this.portVO.platformResblockId = this.popModel.platformResblockId;

        this.getHshColumn("portVO", this.portVO);
        this.popVisible = false;
        this.popResblockVisible = false;
      } else {
        if (this.popModel.housingEstateOptions.length) {
          return this.$message.error("请选择弹窗中的选项匹配小区");
        }

        return this.$message.error("请输入小区或关键字后，点击搜索");
      }
    },
  },
};
</script>

<style scoped>
.cell {
  border-left: 1px solid #dfe6ec;
  border-top: 1px solid #dfe6ec;
  padding: 5px 10px;
}
.reject-input >>> .el-input__inner {
  border-color: red;
}
.pop-box {
  position: absolute;
}
.select-box {
  position: absolute;
  overflow: hidden;
  min-width: 178px;
  max-width: 278px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 12px;
  border: solid 1px #dfe4ed;
  border-radius: 4px;
}

.select-box .select-scroll {
  overflow-y: auto;
  overflow-x: hidden;
  background: #fff;
  max-height: 260px;
}

.select-view {
  padding: 6px 0;
}

.select-box .item {
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  cursor: pointer;
}

.select-box .item:hover {
  background-color: #f5f7fa;
}

.triangle {
  position: absolute;
  display: block;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 6px;
  border-top-width: 0;
  border-bottom-color: #e6ebf5;
  left: 35px;
  top: 6px;
}
.triangle::after {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #fff;
  transform: translateX(-50%);
  top: 2px;
}

.item.text-gray {
  color: #808080;
}
</style>
